package org.buptsse.ui;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterOneActivity extends Activity {

	
	private Handler handler=new Handler()
	{

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;

			case APPConstant.UploadUserDataError:
				Toast.makeText(getApplicationContext(), "更新数据失败", 1000).show();
				break;
				
			case APPConstant.UploadUserDataFinish:
				Intent intent=new Intent();
				intent.setClass(RegisterOneActivity.this, RegisterTwoActivity.class);
				startActivity(intent);
				break;
			}
			super.handleMessage(msg);
		}
		
	};
	
	private TextView usernameTextView,degreeTextView,schoolTextView,firstSubjectTextView,secondSubjectTextView;
	private EditText emailEditText,phoneEditText;
	private Button nextStepButton;
	
	private int selectedFirstSubject=0;

	private String[] eduNo = new String[] {"本科","硕士","博士"};
	//private String[] schoolNo = new String[] {"清华大学","北京大学","北京邮电大学"};
	private String[] firstSubjectList = { "计算机科学与技术", "信息与通信工程", "电子科学与技术", "机械工程", "土木工程", "水利工程"};
    private String[][] secondSubject=new String[6][];
    private String[] schoolNo={"北京大学","北京邮电大学","北京师范大学","北京航空航天大学","北京理工大学","北京交通大学","北京科技大学"};
	
    private void eduDialog() {
		new AlertDialog.Builder(this).setTitle("教育程度")
				.setItems(eduNo, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						degreeTextView.setText(eduNo[which].toString());
					}
				}).show();
	}
	
	private void schoolDialog() {
		new AlertDialog.Builder(this).setTitle("所在学校")
				.setItems(schoolNo, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						schoolTextView.setText(schoolNo[which].toString());
					}
				}).show();
	}
	
	private void firstSubjectDialog()
	{
		new AlertDialog.Builder(this).setTitle("一级学科")
		.setItems(firstSubjectList, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				firstSubjectTextView.setText(firstSubjectList[which]);
				selectedFirstSubject=which;
			}
		}).show();
	}
	
	private void secondSubjectDialog()
	{
		new AlertDialog.Builder(this).setTitle("二级学科")
		.setItems(secondSubject[selectedFirstSubject], new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				secondSubjectTextView.setText(secondSubject[selectedFirstSubject][which]);
			}
		}).show();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		secondSubject[0]=new String[3];
        secondSubject[0][0] = "计算机系统结构";
        secondSubject[0][1] = "计算机软件与理论";
        secondSubject[0][2] = "计算机应用技术";
        secondSubject[1]=new String[2];
        secondSubject[1][0] = "通信与信息系统";
        secondSubject[1][1] = "信号与信息处理";
        secondSubject[2]=new String[4];
        secondSubject[2][0] = "物理电子学";
        secondSubject[2][1] = "电路与系统";
        secondSubject[2][2] = "微电子学与固体电子学";
        secondSubject[2][3] = "电磁场与微波技术";
        secondSubject[3]=new String[4];
        secondSubject[3][0] = "机械制造及其自动化";
        secondSubject[3][1] = "机械电子工程";
        secondSubject[3][2] = "机械设计及理论";
        secondSubject[3][3] = "车辆工程";
        secondSubject[4]=new String[6];
        secondSubject[4][0] = "岩土工程";
        secondSubject[4][1] = "结构工程";
        secondSubject[4][2] = "市政工程";
        secondSubject[4][3] = "供热、供燃气、通风及空调工程";
        secondSubject[4][4] = "防灾减灾工程及防护工程";
        secondSubject[4][5] = "桥梁与隧道工程";
        secondSubject[5]=new String[5];
        secondSubject[5][0] = "水文学及水资源";
        secondSubject[5][1] = "水力学及河流动力学";
        secondSubject[5][2] = "水工结构工程";
        secondSubject[5][3] = "水利水电工程";
        secondSubject[5][4] = "港口、海岸及近海工程";
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 去掉任务条
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.lregister_one);
		usernameTextView=(TextView) findViewById(R.id.username);
		usernameTextView.setText(GloableInstance.user.getName());
		degreeTextView=(TextView)findViewById(R.id.degree);
		degreeTextView.setText(eduNo[0]);
		degreeTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				eduDialog();
			}
		});
		emailEditText=(EditText) findViewById(R.id.email);
		phoneEditText=(EditText) findViewById(R.id.phone);
		schoolTextView=(TextView) findViewById(R.id.school);
		schoolTextView.setText(schoolNo[0]);
		schoolTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				schoolDialog();
			}
		});
		firstSubjectTextView=(TextView) findViewById(R.id.first_subject);
		firstSubjectTextView.setText(firstSubjectList[0]);
		firstSubjectTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				firstSubjectDialog();
			}
		});
		secondSubjectTextView=(TextView) findViewById(R.id.second_subject);
		secondSubjectTextView.setText(secondSubject[0][0]);
		secondSubjectTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				secondSubjectDialog();
			}
		});
		
		nextStepButton=(Button) findViewById(R.id.nextstep);
		nextStepButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				goToNext();
			}
		});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK)
		{
			
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void goToNext()
	{
		String degree=degreeTextView.getText().toString();
		String email=emailEditText.getText().toString();
		String phoneNumber=phoneEditText.getText().toString();
		if(checkEmailAddress(email)==false)
		{
			Toast.makeText(getApplicationContext(), "邮箱输入错误", 1000).show();
			return;
		}
		if(checkPhoneNumber(phoneNumber)==false)
		{
			Toast.makeText(getApplicationContext(), "电话号码格式错误", 1000).show();
			return;
		}
		String school=schoolTextView.getText().toString();
		String firstSubject=firstSubjectTextView.getText().toString();
		String secondSubject=secondSubjectTextView.getText().toString();
		UploadUserDataThread ut=new UploadUserDataThread(this , email, degree, phoneNumber, school, firstSubject, secondSubject);
		ut.start();
	}
	
	private boolean checkEmailAddress(String address)
	{
		return true;
	}
	
	private boolean checkPhoneNumber(String phoneNumber)
	{
		return true;
	}
	
	private class UploadUserDataThread extends Thread
	{
		Context context;
		String email,degree,phoneNumber,school,firstSubject,secondSubject;
		public UploadUserDataThread(Context context,String email,String degree,String phoneNumber,String school,String firstSubject,String secondSubject)
		{
			this.context=context;
			this.email=email;
			this.degree=degree;
			this.phoneNumber=phoneNumber;
			this.school=school;
			this.firstSubject=firstSubject;
			this.secondSubject=secondSubject;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("username", GloableInstance.user.getName()));
			param.add(new BasicNameValuePair("password", GloableInstance.user.getPassword()));
			param.add(new BasicNameValuePair("email", email));
			param.add(new BasicNameValuePair("degree", degree));
			param.add(new BasicNameValuePair("phone", phoneNumber));
			param.add(new BasicNameValuePair("school", school));
			param.add(new BasicNameValuePair("firstSubject", firstSubject));
			param.add(new BasicNameValuePair("secondSubject", secondSubject));
			try {
				String result=HttpHelper.sendPost(APPConstant.uploadUserDataUrl, param);
				//System.out.println("RegistOneAcitvity, result:"+result);
				//System.out.println("result length:"+result.length());
				//System.out.println("success length"+("success").length());
				if(result.contains("success"))
				{
					//System.out.println("in success block");
					Message msg=handler.obtainMessage(APPConstant.UploadUserDataFinish);
					handler.sendMessage(msg);
					GloableInstance.user.setMail(email);
					GloableInstance.user.setDegree(degree);
					GloableInstance.user.setPhoneNumber(phoneNumber);
					GloableInstance.user.setSchool(school);
					GloableInstance.user.setFirstSubject(firstSubject);
					GloableInstance.user.setSecondSubject(secondSubject);
				}else {
					Message msg=handler.obtainMessage(APPConstant.UploadUserDataError);
					handler.sendMessage(msg);
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}